import systemUserService, {
	type SystemUserItem,
} from "@/api/services/systemUserService";
import {
	PlusOutlined,
	SearchOutlined,
	ReloadOutlined,
} from "@ant-design/icons";
import {
	Button,
	Card,
	Form,
	Input,
	Select,
	Row,
	Col,
	Space,
	Table,
	Tag,
	message,
	Popconfirm,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useCallback, useEffect, useState } from "react";
import UserModal from "./user-modal";

const UserList = () => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState<SystemUserItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modalVisible, setModalVisible] = useState(false);
	const [currentUser, setCurrentUser] = useState<SystemUserItem | null>(null);

	const fetchUsers = useCallback(
		async (page = currentPage, limit = pageSize) => {
			try {
				setLoading(true);
				const values = await form.validateFields();
				const res = await systemUserService.userList({
					page,
					limit,
					...values,
				});
				setData(res.items);
				setTotal(res.total);
			} catch (error) {
				message.error("获取数据失败");
			} finally {
				setLoading(false);
			}
		},
		[currentPage, pageSize, form],
	);

	const handleDelete = async (id: number) => {
		try {
			await systemUserService.userDelete(id);
			message.success("删除成功");
			fetchUsers(currentPage, pageSize);
		} catch (error) {
			message.error("删除失败");
		}
	};

	useEffect(() => {
		fetchUsers();
	}, [currentPage, pageSize, fetchUsers]);

	const columns: ColumnsType<SystemUserItem> = [
		{
			title: "用户名",
			dataIndex: "username",
		},
		{
			title: "昵称",
			dataIndex: "nickname",
		},
		{
			title: "邮箱",
			dataIndex: "email",
		},
		{
			title: "手机号",
			dataIndex: "mobile",
		},
		{
			title: "角色",
			dataIndex: ["role", "name"],
		},
		{
			title: "状态",
			dataIndex: "status",
			render: (status: number) => (
				<Tag color={status === 1 ? "success" : "error"}>
					{status === 1 ? "启用" : "禁用"}
				</Tag>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			render: (time: number) =>
				dayjs(time * 1000).format("YYYY-MM-DD HH:mm:ss"),
		},
		{
			title: "操作",
			key: "action",
			render: (_, record) => (
				<Space size="middle">
					<Button
						type="link"
						onClick={() => {
							setCurrentUser(record);
							setModalVisible(true);
						}}
					>
						编辑
					</Button>
					<Popconfirm
						title="确定要删除此用户吗？"
						onConfirm={() => handleDelete(record.id)}
						okText="确定"
						cancelText="取消"
					>
						<Button type="link" danger>
							删除
						</Button>
					</Popconfirm>
				</Space>
			),
		},
	];

	return (
		<>
			<Card>
				<Form form={form} onFinish={() => fetchUsers(1)}>
					<Row gutter={[16, 16]}>
						<Col span={24} lg={6}>
							<Form.Item name="username" className="!mb-0">
								<Input placeholder="请输入用户名" allowClear />
							</Form.Item>
						</Col>
						<Col span={24} lg={6}>
							<Form.Item name="status" className="!mb-0">
								<Select
									placeholder="请选择状态"
									allowClear
									style={{ width: "100%" }}
									options={[
										{
											label: "启用",
											value: 1,
										},
										{
											label: "禁用",
											value: 0,
										},
									]}
								/>
							</Form.Item>
						</Col>
						<Col span={24} lg={12}>
							<div className="flex justify-end">
								<Space>
									<Button
										icon={<ReloadOutlined />}
										onClick={() => {
											form.resetFields();
											fetchUsers(1);
										}}
									>
										重置
									</Button>
									<Button
										type="primary"
										htmlType="submit"
										icon={<SearchOutlined />}
									>
										查询
									</Button>
								</Space>
							</div>
						</Col>
					</Row>
				</Form>
			</Card>

			<Card
				title="用户列表"
				extra={
					<Button
						type="primary"
						icon={<PlusOutlined />}
						onClick={() => {
							setCurrentUser(null);
							setModalVisible(true);
						}}
					>
						新增用户
					</Button>
				}
			>
				<Table
					columns={columns}
					dataSource={data}
					rowKey="id"
					loading={loading}
					pagination={{
						total,
						current: currentPage,
						pageSize,
						showSizeChanger: true,
						showQuickJumper: true,
						showTotal: (total) => `共 ${total} 条记录`,
						onChange: (page, pageSize) => {
							setCurrentPage(page);
							setPageSize(pageSize);
							fetchUsers(page, pageSize);
						},
					}}
				/>

				<UserModal
					open={modalVisible}
					user={currentUser}
					onSuccess={() => {
						setModalVisible(false);
						fetchUsers();
					}}
					onCancel={() => setModalVisible(false)}
				/>
			</Card>
		</>
	);
};

export default UserList;
